<template>
    <div class="job-index-root">
        <div class="content_cls">
            <left class="job_left_cls"
                  v-bind:entries="entries"
                  v-bind:active-entry="gc"
                  v-on:click-item="clickItem"></left>
            <job-list class="job_list_cls"
                      v-bind:brow="leftActiveCache" v-bind:job_list="jobsCache"
                      @click-which="operateData">
            </job-list>
        </div>
        <el-dialog title="提示" :visible.sync="showDialogQ">
            <republish-dialog :type="this.republishType"
                              @click-which="clickRepublish"></republish-dialog>
        </el-dialog>
        <resume-pagination :total="pageTotal" :size="pageSize" @hasPage="pageIndexChange"></resume-pagination>

    </div>
</template>

<script>
  import Left from '../Left'
  import JobList from './JobList'
  import _g from '../../assets/utils/global'
  import _subject from '../../assets/utils/subject'
  import * as qs from 'qs'
  import * as _ from 'underscore'
  import resumePagination from '../../views/resume/resume-pagination'
  import RepublishDialog from './RepublishDialog'

  export default {
    name: 'index-job',
    props: {
      entries: {
        type: Array,
        default: function() {
          return [{ group: '职位管理', children: ['审核职位', '开放职位', '暂停职位', '关闭职位', '草稿'] }]
        }
      }
    },
    data() {
      return {
        gc: { g: 0, c: 0 },
        serverJobs: [],
        jobsTemp: [],
        pageTotal: 0,
        pageIndex: 1,
        pageSize: 10,
        queryState: ['@0,2@', '@1@0', '@1@1', '@1@2', '@@3'],
        serverOptions: [],
        showDialogQ: false,
        republishType: 0,
        currentJobId: 0
      }
    }
    ,
    components: {
      RepublishDialog,
      Left: Left,
      JobList: JobList,
      resumePagination
    }
    ,
    computed: {
      jobsCache: function() {
        let temp = []
        for (let i = 0; i < this.serverJobs.length; i++) {
          let t = this.serverJobs[i]
          // temp.push({
          //   id: i,
          //   job_name: '职位名称',
          //   job_salary: '10-20W',
          //   salary_period: '/2年',
          //   job_city: '工作城市',
          //   job_period: '工作年限',
          //   job_req: '执业要求',
          //   job_num: '招聘人数',
          //   job_info: '2019-04-01 发布',
          //   job_time_tip: '有效期剩余',
          //   job_time: '20天',
          //   job_flow: this.getFlow(this.gc.c)
          // })
          temp.push({
            id: i,
            server_id: t.id,
            job_name: t.name,
            salary_tax: (t.tax === 0 ? '税前' : '税后'),
            job_salary: this.nullOr(t.salaryPerMonthLow, '0') + '-' + this.nullOr(t.salaryPerMonthHigh, '0') + 'W',
            salary_period: '/' + this.nullOr(t.salaryCount, '0') + '年',
            job_city: _.isNull(t.city) ? '城市未知' : t.city,
            job_period: this.getText(37, t.workTime),
            job_req: t.licenseTypeIdStr,
            job_num: (t.recruitingNumbers ? t.recruitingNumbers : '未知') + '人',
            job_info: t.checkTime === null ? (String(t.rdtime).substr(0, String(t.rdtime).indexOf(' ')) + '发布') : (String(t.checkTime).substr(0, String(t.checkTime).indexOf(' ')) + '审核'),
            job_time_tip: '有效期剩余',
            job_time: _.isNull(t.validity) ? '未知' : (this.getRestDay(t.checkState, t.validity) + '天'),
            job_flow: this.getFlow(t.jobState, t.checkState)
          })
        }
        return temp
      }
      ,
      leftActiveCache: function() {
        return this.entries[this.gc.g].children[this.gc.c]
      }
    }
    ,
    methods: {
      getRestDay(state, num) {
        state = Number(state)
        num = Number(num)
        if (num === 0) {
          if (state === 1) {
            return 1
          } else {
            return 0
          }
        }
        return num
      },
      deleteDraft(sid) {
        _g.apiPost('/company/deleteByPrimaryKey.do', { jobId: sid })
          .then(res => {
            console.log('start delete draft', res)
            if (res && res.status === 0) {
              console.log('delete draft result', res.data)
              _g.message('您的职位信息已刪除', 'success')
              this.loadData()
            }
          })
      },
      clickRepublish(type, which) {
        this.showDialogQ = false
        if (which === 1) {
          if (type === 0) {
            this.changeServerState(this.currentJobId, 0, '重新发布')
          } else {
            //联系顾问
            _g.getCache().gc.g = 1
            _g.getCache().gc.c = 1
            this.$router.push({ path: '/communication/Corporate' })
          }
        }
      },
      validateRepublish(id) {
        _g.apiPost('/company/selectvalidityTime.do', { jobId: id })
          .then(res => {
            console.log('validate republish result', res)
            if (res && res.status === 0) {
              if (Number(res.data) === 3) {
                this.republishType = 1
                this.showDialogQ = true
              } else {
                this.republishType = 0
                this.showDialogQ = true
              }
            }
          })
      },
      getText: function(typeId, id) {
        let t = _.find(this.serverOptions[typeId], o => {
          return o.id === id
        })
        return _.isUndefined(t) ? '未知' : t.content
      },
      nullOr: function(o, text) {
        return _.isNull(o) ? text : o
      },
      //点击左侧栏
      clickItem: function(g, c) {
        this.gc = { g: g, c: c }
        this.pageIndex = 1
        //刷选数据和更新
        this.loadData()
      },
      //获取职位状态
      getFlow: function(job, state) {
        if (state === 0 || state === 2) {
          if (job === 3) {
            return '草稿'
          }
          if (state === 0) {
            return '待审核'
          } else if (state === 2) {
            return '不通过'
          }
        } else if (state === 1) {
          //审核通过
          if (job === 0 || job === null) {
            return '开放职位'
          } else if (job === 1) {
            return '暂停职位'
          } else if (job === 2) {
            return '关闭职位'
          }
        }
      },
      //刷新数据
      refreshData: function() {
        console.log('refresh', this.gc)
        this.serverJobs.splice(this.serverJobs, this.serverJobs.length)
        _.each(this.jobsTemp, o => {
          if (this.gc.g === 0) {
            if (this.gc.c === 0) {
              if (o.checkState === 0 || o.checkState === 2) {
                if (o.jobState !== 3) {
                  this.serverJobs.push(o)
                }
              }
            } else if (this.gc.c === 1) {
              //开放职位
              if (o.checkState === 1 && (o.jobState === 0 || o.jobState === null)) {
                this.serverJobs.push(o)
              }
            } else if (this.gc.c === 2) {
              if (o.checkState === 1 && o.jobState === 1) {
                this.serverJobs.push(o)
              }
            } else if (this.gc.c === 3) {
              if (o.checkState === 1 && o.jobState === 2) {
                this.serverJobs.push(o)
              }
            } else if (this.gc.c === 4) {
              if (o.checkState !== 1 && o.jobState === 3) {
                this.serverJobs.push(o)
              }
            }
          }
        })
      },
      pageIndexChange: function(n) {
        _subject.log('page index', n)
        this.pageIndex = n
        this.loadData()
      },
      //加载服务器数据
      loadData: function() {
        //请求后台数据
        let params = {
          currPageNo: this.pageIndex,
          pageSize: this.pageSize,
          orderBy: 'desc',
          state: this.queryState[this.gc.c]
        }
        console.log('job list query', qs.stringify(params))
        _g.apiPost('/company/selectJobInfoByCompanyId.do', params)
          .then(res => {
            console.log('job list result', res)
            if (res && res.status === 0) {
              this.jobsTemp = res.data.list
              this.pageTotal = res.data.total
              this.refreshData()
            }
          })
        _g.apiPost('/company/selectStaticData.do', { state: _.range(1, 44).join(',') })
          .then(res => {
            console.log('jd query all options result')
            console.log(res)
            if (!_.isNull(res) && res.status === 0) {
              this.serverOptions = res.data
            }
          })
      },
      //操作数据
      operateData: function(ops, sid) {
        this.currentJobId = sid
        if (ops === 'edit') {
          //通知顶部栏变样式
          _subject.page.next(-1)
          //通知职位信息某些字段不可编辑
          let disabled = '0'
          if (this.gc.c === 0) {
            disabled = '2'
          } else if (this.gc.c === 1 || this.gc.c === 2) {
            disabled = '3'
          }
          this.$router.push({
            path: '/editjob',
            query: { jobServerId: sid, disabled: disabled, which: String(this.gc.c) }
          })
        } else if (ops === 'pause') {
          this.changeServerState(sid, 1, '暂停')
        } else if (ops === 'online') {
          this.changeServerState(sid, 3, '上线')
        } else if (ops === 'republish') {
          this.validateRepublish(sid)
        } else if (ops === 'delete') {
          console.log('delete draft', sid)
          this.deleteDraft(sid)
        }
      },
      changeServerState: function(sid, state, text) {
        _g.apiPost('/company/updateJobState.do', { jobId: sid, jobState: state, type: 2 })
          .then(res => {
            console.log('pause job result')
            console.log(res)
            if (!_.isNull(res) && res.status === 0) {
              _g.message('您的职位信息已' + text, 'success')
              this.loadData()
            }
          })
      }
    },
    created() {
      if (this.$route.query.hasOwnProperty('which')) {
        this.gc.g = 0
        this.gc.c = Number(this.$route.query.which)
      }
      this.loadData()
    }
  }
</script>

<style lang="scss" scoped>
    .job-index-root {
        width: 100vw;
        /*height: 85vh;*/
        display: flex;
        flex-direction: column;
        align-items: center;
        background: #f2f2f2;
    }

    .job_left_cls {
        margin-top: 21px;
    }

    .job_list_cls {
        margin-left: 19px;
    }

    .content_cls {
        width: 1200px;
        display: flex;
        justify-items: center;
        /*border: 2px solid red;*/
        position: relative;
    }

    .nav_cls {
        margin-top: 20px;
        margin-bottom: 232px;
    }
</style>
